from .Sqlite3Common import conver_bytes_to_int


class SerialTypeCodesFormat:
    SerialTypeMap = {
        0: [0, None],
        1: [1, int],
        2: [2, int],
        3: [3, int],
        4: [4, int],
        5: [6, int],
        6: [8, int],
        7: [8, float],
        8: [0, 0],
        9: [0, 1],
    }

    def convert(self, typei, data, offset):
        res = None
        size = 0
        if typei in SerialTypeCodesFormat.SerialTypeMap:
            res, size = self.read_number(typei, data, offset)
        elif (typei - 12) % 2 == 0:  # BLOB 当前不需要此数据
            size = (typei - 12) / 2
        elif (typei - 13) % 2 == 0:  # Text
            res, size = self.read_text(typei, data, offset)
        return res, int(size)

    def read_number(self, typei, data, offset):
        res = None
        size = 0
        signs = SerialTypeCodesFormat.SerialTypeMap[typei]
        if typei in [0, 8, 9]:
            size = signs[0]
            res = signs[1]
        elif typei in range(1, 7):
            size = signs[0]
            res = conver_bytes_to_int(data[offset: offset+size])
        elif typei == 8:
            size = signs[0]
            res = 0

        return res, size

    def read_text(self, typei: int, data: bytes, offset: int):
        size = int((typei - 13) / 2)
        text = data[offset:offset+size]
        return str(text, 'utf-8'), size

    @staticmethod
    def type_s_sum(type_ss: list):
        def cal_size(flag):
            if flag in SerialTypeCodesFormat.SerialTypeMap:
                return SerialTypeCodesFormat.SerialTypeMap[flag][0]
            elif (flag - 12) % 2 == 0:  # BLOB 当前不需要此数据
                return int((flag - 12) / 2)
            elif (flag - 13) % 2 == 0:  # Text
                return int((flag - 13) / 2)
            return 0
        res = 0
        for type_i in type_ss:
            res += cal_size(type_i)
        return res

    @staticmethod
    def data_type(type_value):
        if type_value == 0:
            return type(None)
        elif type_value in range(1, 10):
            return int
        elif(type_value - 13) % 2 == 0:
            return str
        else:
            return bytes
